//
//  UploadImageTool.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/19.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "UploadImageTool.h"
#import"UploadImageTool.h"
#import "GTMBase64.h"
#import"AFNetworking.h"
#include <CommonCrypto/CommonCrypto.h>
#import "QNUploadManager.h"
#import "UIImage+ResizeMagick.h"
#import"AFNetworkActivityIndicatorManager.h"


#define QiNiuBaseUrl @"http://7xozpn.com2.z0.glb.qiniucdn.com/"


@implementation UploadImageTool
//给图片命名
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
//获取七牛的token

//七牛上传凭证
+ (NSString *)makeToken:(NSString *)accessKey secretKey:(NSString *)secretKey
{
    
    NSString *AK =@"5sczmEmyO7d-_pou0kR2UOPL3gKY_J9nZTtsCIWY";
    NSString *SK = @"1xalhtp2_-h0nxr0mqzRCxadBpTT8Qybl4NJbdb9";
    
    const char *secretKeyStr = [SK UTF8String];
    NSString *policy = [UploadImageTool marshalImage];
    
    NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *encodedPolicy = [GTMBase64 stringByWebSafeEncodingData:policyData padded:TRUE];
    const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding];
    
    char digestStr[CC_SHA1_DIGEST_LENGTH];
    bzero(digestStr, 0);
    
    CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr);
    
    NSString *encodedDigest = [GTMBase64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE];
    
    NSString *token = [NSString stringWithFormat:@"%@:%@:%@",  AK, encodedDigest, encodedPolicy];
    
    return token;//得到了token
}
+ (NSString *)marshalImage
{
    time_t deadline;
    time(&deadline);//返回当前系统时间
    int expires;
    deadline += (expires > 0) ? expires : 3600; // +3600秒,即默认token保存1小时.

    NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
     NSString *fileName = [NSString stringWithFormat:@"%@_%@.jpg", [self getDateTimeString], [self randomStringWithLength:8]];
    NSString *string =[NSString stringWithFormat:@"kingop-test:%@",fileName];
    [dic setObject:string forKey:@"scope"];//根据
    [dic setObject:deadlineNumber forKey:@"deadline"];

    NSString *json =[Common dictionaryToJson:dic];

    return json;
}





//+ (void)upLoadImage
//{
//    
//    NSString *AK =@"你的AccessKey";
//    NSString *SK = @"你的SecretKey";
//    NSString *token = [UploadImageTool makeToken:AK secretKey:SK];
//    NSLog(@"token = %@",token);
//    
//    QNUploadManager *upManager =[[QNUploadManager alloc]init];
//    
//    
//    NSString *str =[Common dictionaryToJson:dic];
//    NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding]; ;//转为JSON格式，便于下载
//
//    
//    [upManager putData:data key:@"aaa" token:token
//              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//                  NSLog(@"info = %@\n", info);
//                  NSLog(@"key = %@\n",key);
//                  NSLog(@"resp = %@\n", resp);
//              } option:nil];
//    
////    QNUploadManager *upManager = [[QNUploadManager alloc] init];
////    
////    // Your Token Here, See: http://developer.qiniu.com/docs/v6/api/reference/security/upload-token.html
////    NSString *token = @"";
////    
////    // Load Local Image
////    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"pixar" ofType:@"jpeg"];
////    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
////    
////    NSString *fileName = [NSString stringWithFormat:@"%@_%@.jpg", [self getDateTimeString], [self randomStringWithLength:8]];
////    
////    // ------------------- Test putData -------------------------
////    //    NSData *data = [@"Hello, World!" dataUsingEncoding : NSUTF8StringEncoding];
////    NSData *data = [image resizedAndReturnData];
////    [upManager putData:data
////                   key:fileName
////                 token:token
////              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
////                  
////                  NSLog(@" --->> Info: %@  ", info);
////                  NSLog(@" ---------------------");
////                  NSLog(@" --->> Response: %@,  ", resp);
////              }
////                option:nil];
//    
//}
+ (NSString *)getDateTimeString
{
    NSDateFormatter *formatter;
    NSString        *dateString;
    
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    
    dateString = [formatter stringFromDate:[NSDate date]];
    
    return dateString;
}


+ (NSString *)randomStringWithLength:(int)len
{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (int i=0; i<len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((int)[letters length])]];
    }
    
    return randomString;
}
//上传单张图片

+ (void)uploadImage:(UIImage*)image progress:(QNUpProgressHandler)progress success:(void(^)(NSString*url))success failure:(void(^)())failure {
    
    [UploadImageTool getQiniuUploadToken:^(NSString*token) {
        
        NSData*data =UIImageJPEGRepresentation(image,0.01);
        
        if(!data) {
            
            if(failure) {
                
                failure();
                
            }
            
            return;
            
        }
        
        NSString*fileName =[NSString stringWithFormat:@"kingop-test:%@",[Common createFileName:@".jpg"]] ;
        QNUploadOption*opt = [[QNUploadOption alloc]initWithMime:nil
                              
                                                 progressHandler:progress
                              
                                                          params:nil
                              
                                                        checkCrc:NO
                              
                                              cancellationSignal:nil];
        
        QNUploadManager*uploadManager = [QNUploadManager sharedInstanceWithConfiguration:nil];
        
        [uploadManager putData:data
         
                           key:fileName
         
                         token:token
         
                      complete:^(QNResponseInfo*info,NSString*key,NSDictionary*resp) {
                          
                          if(info.statusCode==200&& resp) {
                              
                              NSString*url= [NSString stringWithFormat:@"%@%@",QiNiuBaseUrl, resp[@"key"]];
                              
                              if(success) {
                                  
                                  success(url);
                                  
                              }
                              
                          }
                          
                          else{
                              
                              if(failure) {
                                  
                                  failure();
                                  
                              }
                              
                          }
                          
                      }option:opt];
        
    }failure:^{
        
    }];
    
}

//上传多张图片

//+ (void)uploadImages:(NSArray*)imageArray progress:(void(^)(CGFloat))progress success:(void(^)(NSArray*))success failure:(void(^)())failure
//
//{
//    
//    NSMutableArray*array = [[NSMutableArray alloc]init];
//    
//    __block CGFloattotalProgress =0.0f;
//    
//    __block CGFloatpartProgress =1.0f/ [imageArray count];
//    
//    __block NSUIntegercurrentIndex =0;
//    
//    QiniuUploadHelper*uploadHelper = [QiniuUploadHelper sharedUploadHelper];
//    
//    __weaktypeof(uploadHelper) weakHelper = uploadHelper;
//    
//    uploadHelper.singleFailureBlock= ^() {
//        
//        failure();
//        
//        return;
//        
//    };
//    
//    uploadHelper.singleSuccessBlock= ^(NSString*url) {
//        
//        [array addObject:url];
//        
//        totalProgress += partProgress;
//        
//        progress(totalProgress);
//        
//        currentIndex++;
//        
//        if([arraycount] == [imageArraycount]) {
//            
//            success([arraycopy]);
//            
//            return;
//            
//        }else{
//            
//            NSLog(@"---%ld",currentIndex);
//            
//            [UploadImageTool uploadImage:imageArray[currentIndex] progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock];
//            
//        }
//        
//    };
//    
//    [UploadImageTool uploadImage:imageArray[0] progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock];
//    
//}




@end
